<template>
	<view class="arrears-pages">
		<checkbox-group class="info-block" @change="checkboxChange">
			<SelectHouse :info="selectInfo"></SelectHouse>
			<view class="info-item" v-for="item in list" :key="item.id">
				<view class="title-item">
					<checkbox :value="item.id" :checked="form.checktId.some(data=>Number(data)===item.id)"
						style="transform:scale(0.7);" class="checkbox" color="#fb4744" />
					<view class="title">{{item.name}}</view>
				</view>
				<view class="arrears-info">
					<view class="arrears-item">
						<view class="info-title">欠费时段</view>
						<view class="info-text">{{item.startTime}}至{{item.endTime}}</view>
					</view>
					<view class="arrears-item">
						<view class="info-title">欠费金额</view>
						<view class="info-price">{{item.amount}}</view>
						<view class="unit">元</view>
						<view class="iconfont icon-a-jinggao1" @click="jumpToCalculationPage(item)"></view>
					</view>
				</view>
			</view>
		</checkbox-group>
		<view class="bottom-block">
			<view class="bottom-info">
				<checkbox-group @change="allCheckEvent">
					<checkbox :value="allIds.join(',')" :checked="allIds.length==form.checktId.length"
						style="transform:scale(0.7);" color="#fb4744" />
				</checkbox-group>
				<view class="title">全选</view>
				<view class="select-item">
					<view class="text">已选{{form.checktId.length}}项</view>
					<view class="price-item">
						<view class="price-name">总金额</view>
						<view class="price">￥{{totalPrice}}</view>
					</view>
				</view>
			</view>
			<view class="small-btn normal" @click="submit">去支付</view>
		</view>
	</view>
</template>

<script>
	import {
		SelectHouse
	} from '@/components/SelectHouse.vue'
	import {
		getStorage
	} from '@/util/auth.js';
	import {
		validate
	} from '@/util/validate.js';
	import {
		getFwInfoByIdApi
	} from '@/api/rent_payment.js'
	import {
		payment
	} from '@/api/payment.js';
	export default {
		components: {
			SelectHouse
		},
		data() {
			return {
				selectInfo: {},
				totalPrice: 0,
				idValue: '',
				unitPricePerSquare: '',
				calculatedPrice: '',
				buildingArea: '',
				usableArea: '',
				houseType: '',
				payableRent: '',
				payablePropertyFee: '',
				payableLateFee: '',
				rentArrears: '', //房租欠费
				rentMonthsBetween: '', //房租欠费时间（月）
				lateFee: '', //滞纳金
				newDaysBetween: '', //滞纳时间（天）
				propertyFeeArrears: '', //物业欠费
				propertyMonthsBetween: '', //物业欠费时间（月）
				allIds: [],
				list: [],
				form: {
					checktId: [],
				},
				rule: {
					checktId: {
						name: '',
						required: false,
						validator: function(value, form, callback) {
							if (value.length == 0) {
								callback('请选择缴纳项目！');
							}
							callback();
						}
					},
				}
			}
		},
		methods: {
			jumpToCalculationPage(data) {
				if (data.name.includes('房租')) {
					uni.navigateTo({
						url: '/page_pack/rent_payment/rent_calculator?rentMonthsBetween=' + data.monthsBetween
					});
				} else if (data.name.includes('滞纳金')) {
					uni.navigateTo({
						url: '/page_pack/rent_payment/late_fee_calculator'
					});
				} else if (data.name.includes('物业')) {
					uni.navigateTo({
						url: '/page_pack/property/property_calculator'
					});
				}
			},
			checkboxChange(e) {
				console.log('单选/多选:', e);
				this.totalPrice = 0;
				this.form.checktId = e.detail.value; // 当前选中的ID数组

				// 筛选出选中的项
				let filteredArray = this.list.filter(item =>
					this.form.checktId.includes(String(item.id))
				);

				console.log(filteredArray)
				// 根据name匹配并累加amount
				filteredArray.forEach(item => {
					this.totalPrice += Number(item.amount);
					this.totalPrice = parseFloat(this.totalPrice.toFixed(2));

					// 动态属性赋值：根据item.name匹配字段
					if (item.name.includes('房租') && this.rentArrears !== undefined) {
						this.rentArrears = (Number(this.rentArrears || 0) + Number(item.amount)).toFixed(
							2);
						this.rentMonthsBetween = item.monthsBetween
						this.payableRent = item.payableTotalPrice
					} else if (item.name.includes('滞纳金') && this.lateFee !== undefined) {
						this.lateFee = (Number(this.lateFee || 0) + Number(item.amount)).toFixed(2);
						this.newDaysBetween = item.newDaysBetween
						this.payableLateFee = item.payableTotalPrice
					} else if (item.name.includes('物业') && this.propertyFeeArrears !== undefined) {
						this.propertyFeeArrears = (Number(this.propertyFeeArrears || 0) + Number(item
							.amount)).toFixed(2);
						console.log(this.propertyFeeArrears)
						this.propertyMonthsBetween = item.monthsBetween
						this.payablePropertyFee = item.payableTotalPrice
					}
				});

			},

			allCheckEvent(e) {
				console.log('全选事件:', e);
				this.totalPrice = 0;
				const isAllChecked = e.detail.value.length > 0 && e.detail.value[0] !== "";

				// 重置所有金额字段
				this.rentArrears = '';
				this.lateFee = '';
				this.propertyFeeArrears = '';

				if (isAllChecked) {
					this.form.checktId = [...this.allIds.map(String)];
					this.totalPrice = this.list.reduce((sum, item) => {
						// 全选时同样根据name匹配字段
						if (item.name.includes('房租') && this.rentArrears !== undefined) {
							this.rentArrears = (Number(this.rentArrears || 0) + Number(item.amount))
								.toFixed(2);
							this.rentMonthsBetween = item.monthsBetween
							this.payableRent = item.payableTotalPrice
						} else if (item.name.includes('滞纳金') && this.lateFee !== undefined) {
							this.lateFee = (Number(this.lateFee || 0) + Number(item.amount)).toFixed(2);
							this.newDaysBetween = item.newDaysBetween
							this.payableLateFee = item.payableTotalPrice
						} else if (item.name.includes('物业') && this.propertyFeeArrears !== undefined) {
							this.propertyFeeArrears = (Number(this.propertyFeeArrears || 0) + Number(item
								.amount)).toFixed(2);
							console.log(this.propertyFeeArrears)
							this.propertyMonthsBetween = item.monthsBetween
							this.payablePropertyFee = item.payableTotalPrice
						}
						return sum + Number(item.amount);
					}, 0);
					this.totalPrice = parseFloat(this.totalPrice.toFixed(2));
				} else {
					this.form.checktId = [];
					this.totalPrice = 0;
				}
			},
			getList() {
				getFwInfoByIdApi({
					id: this.id
				}).then((res) => {
					this.idValue = res.idValue
					this.unitPricePerSquare = res.unitPricePerSquare
					this.calculatedPrice = res.calculatedPrice
					this.buildingArea = res.buildingArea
					this.usableArea = res.usableArea
					this.houseType = res.houseType
					let list = res.arrearsFeesList
					list.forEach((item, index) => {
						item.id = index + 1
					})
					this.list = list.filter(item => item.amount > 0)
					this.list.forEach((item, index) => {
						this.allIds.push(item.id)
					})
				})
			},
			submit() {
				// 验证表单
				if (!validate(this.form, this.rule)) {
					return;
				}

				try {
					// 准备基础支付数据
					const paymentData = this.preparePaymentData();

					// 发起支付
					this.processPayment(paymentData);
				} catch (error) {
					console.error('支付处理出错:', error);
					this.showToast('支付处理出错，请稍后重试');
				}
			},

			// 准备支付数据
			preparePaymentData() {
				// 基础数据
				const data = {
					idValue: this.idValue,
					type: 1,
					beforeAdjustment: this.unitPricePerSquare,
					afterAdjustment: this.calculatedPrice,
					calculatedArea: this.getCalculatedArea(),
					payableRent: this.payableRent,
					payablePropertyFee: this.payablePropertyFee,
					payableLateFee: this.payableLateFee,
					rentLateDays: 0,
					rent: 0,
					rentMonth: 0,
					propertyFee: 0,
					propertyFeeMonth: 0,
					lateFee: 0
				};

				// 处理选中的项目
				this.processSelectedItems(data);

				// 清理空值
				return this.cleanEmptyValues(data);
			},

			// 获取计算面积
			getCalculatedArea() {
				return this.houseType.includes('廉租') || this.houseType.includes('公租') ?
					this.usableArea :
					this.buildingArea;
			},

			// 处理选中的项目
			processSelectedItems(data) {
				const selectedItems = this.list.filter(item =>
					this.form.checktId.includes(String(item.id))
				);

				selectedItems.forEach(item => {
					if (item.name.includes('房租')) {
						data.rentLateDays = item.daysBetween
						data.rentMonth = item.monthsBetween;
						//data.tent = item.amount
						data.rent = 0.01; // 测试值
					} else if (item.name.includes('物业')) {
						data.propertyFeeMonth = item.monthsBetween;
						//data.propertyFee = item.amount
						data.propertyFee = 0.01; // 测试值
					} else if (item.name.includes('滞纳金')) {
						data.lateFee = item.amount;
					}
				});
			},

			// 清理空值
			cleanEmptyValues(data) {
				return Object.fromEntries(
					Object.entries(data).filter(([_, value]) => value !== 0)
				);
			},

			// 处理支付流程
			async processPayment(paymentData) {
				try {
					const res = await payment(paymentData);

					if (!res) {
						this.showToast('支付失败，请联系管理员');
						return;
					}
					this.requestWxPayment(res);
				} catch (error) {
					console.error('支付接口调用失败:', error);
					this.showToast('支付服务暂时不可用');
				}
			},

			// 请求微信支付
			requestWxPayment(paymentResponse) {
				const {
					timeStamp,
					nonceStr,
					package: pkg,
					paySign
				} = paymentResponse;
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp,
					nonceStr,
					package: pkg,
					signType: 'MD5',
					paySign,
					success: () => this.handlePaymentSuccess(),
					fail: (err) => this.handlePaymentFailure(err)
				});
			},

			// 处理支付成功
			handlePaymentSuccess() {
				uni.showToast({
					title: '缴纳成功',
					duration: 2000,
					mask: true,
				});
				uni.redirectTo({
					url: `/page_pack/pay_success/arrears_success?rentArrears=${this.rentArrears}&lateFee=${this.lateFee}&propertyFeeArrears=${this.propertyFeeArrears}&totalPrice=${this.totalPrice}&rentMonthsBetween=${this.rentMonthsBetween}&propertyMonthsBetween=${this.propertyMonthsBetween}`
				});
			},

			// 处理支付失败
			handlePaymentFailure(error) {
				console.error('微信支付失败:', error);
				this.showToast('支付失败，请重试');
			},

			// 显示提示（封装以方便统一修改）
			showToast(message) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: 2000
				});
			}
		},
		onLoad(e) {
			this.id = e.id
			this.getList()
			// this.list.forEach(item => {
			// 	this.allIds.push(item.id)
			// })
		},
		onShow() {
			this.selectInfo = getStorage('selectInfo')
		}
	}
</script>
<style lang="scss" scoped>
	.arrears-pages {


		.info-block {
			padding: 30rpx;

			.info-item {
				background: #fff;
				border-radius: 30rpx;
				margin-top: 30rpx;

				.title-item {
					width: 100%;
					height: 80rpx;
					background: url('https://suzhouqu-static-1306862033.cos.ap-chengdu.myqcloud.com/suzhouHousesLease/uniapp/rent/title_bg.png')no-repeat top;
					background-size: 100% 100%;
					border-radius: 30rpx 30rpx 0 0;
					display: flex;
					align-items: center;
					padding: 0 30rpx;

					.title {
						color: $theme-color;
						font-size: 32rpx;
						font-weight: bold;
					}
				}

				.arrears-info {
					padding: 30rpx 30rpx 30rpx 70rpx;

					.arrears-item {
						display: flex;
						align-items: center;
						font-size: 28rpx;
						line-height: 64rpx;

						.info-title {
							margin-right: 10rpx;
						}

						.info-price {
							color: $theme-color;
							font-weight: bold;
						}

						.iconfont {
							margin-left: 20rpx;
							font-size: 30rpx;
							color: #767676;
						}
					}
				}
			}
		}

		.bottom-block {
			background-color: #fff;
			position: fixed;
			bottom: 0;
			height: 170rpx;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx;

			.bottom-info {
				display: flex;
				align-items: center;

				.title {
					font-size: 30rpx;
					margin-right: 30rpx;
				}

				.select-item {
					.text {
						font-size: 26rpx;
						color: #767676;
						margin-bottom: 10rpx;
					}

					.price-item {
						display: flex;
						align-items: center;

						.price-name {
							font-size: 28rpx;
						}

						.price {
							font-size: 40rpx;
							color: $theme-color;
						}
					}
				}
			}

			.small-btn {
				width: 200rpx;
				height: 80rpx;
			}
		}
	}
</style>